const router = require('koa-router')();
const fs = require('fs');
const path = require('path');
function sleep(ms) {
  return new Promise(resolve =>
    setTimeout(resolve, ms)
  )
};
function saveFile(file) {
  const reader = fs.createReadStream(file.path, {
    autoClose: true, //默认读取完毕后自动关闭
  }); // 创建可读流
  const target = path.join(__dirname, `../../static/upload/${file.name}`);
  const upStream = fs.createWriteStream(target); // 创建可写流
  reader.pipe(upStream); // 可读流通过管道写入可写流
}

router.post('/upload', async (ctx) => {
  const files = ctx.request.files.file; // 获取上传文件
  if (Array.isArray(files)) {
    for (let file of files) {
      saveFile(file);
    }
  } else {
    saveFile(files);
  }
  
  return ctx.body = '上传成功';
})
var AipOcrClient = require("baidu-aip-sdk").ocr;

// 设置APPID/AK/SK
var APP_ID = "24935144";
var API_KEY = "fuVogQqbafeAHToH7AS9aDpg";
var SECRET_KEY = "2dyYz6gtoIOTLBQhw1Pzp6jS7NtppZ1e";

// 新建一个对象，建议只保存一个对象调用服务接口
var client = new AipOcrClient(APP_ID, API_KEY, SECRET_KEY);
router.post('/fetchFile', async (ctx) => {
  try {
    const file = ctx.request.files.file; // 获取上传文件
    console.log(file);
    let options = {};
    // var pdf = "./1.pdf";
    // await sleep(1000);
    let baiduAI = await client.vatInvoicePdf(file.path, options);
    ctx.body = baiduAI
  } catch (e) {
    console.log(e);
  }
})

module.exports = router;